#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Download failed logos with correct URL path from log file
"""

import os
import requests
import re

# 配置
BASE_DOMAIN = "https://www.shanghairanking.cn/"
LOGO_DIR = "logos"
HEADERS = {
    "User-Agent": "Mozilla/5.0 (compatible; DataCollector/1.0; +https://example.com)"
}

os.makedirs(LOGO_DIR, exist_ok=True)

def download_logo_with_correct_path(logo_filename, university_name=""):
    """
    使用正确的路径下载logo图片
    
    Args:
        logo_filename: logo文件名，例如 "4506696400.jpg"
        university_name: 大学名称（可选，用于文件命名）
    """
    # 构造正确的URL路径
    correct_url = f"{BASE_DOMAIN}_uni/logo-jpg/{logo_filename}"
    
    # 生成输出文件名
    ext = os.path.splitext(logo_filename)[1] or ".jpg"
    safe_name = university_name or "university"
    safe_name = "".join(c if c.isalnum() or c in "-_" else "-" for c in safe_name)[:80]
    
    # 查找对应的文件名前缀（数字）
    prefix = None
    for filename in os.listdir(LOGO_DIR):
        if safe_name.lower().replace(" ", "-").replace("_", "-") in filename.lower():
            prefix = filename.split("_")[0]
            break
    
    # 如果找不到前缀，使用默认值
    if prefix is None:
        outfn = os.path.join(LOGO_DIR, f"university_{safe_name}{ext}")
    else:
        outfn = os.path.join(LOGO_DIR, f"{prefix}_{safe_name}{ext}")
    
    # 如果文件已存在，跳过下载
    if os.path.exists(outfn):
        print(f"文件已存在，跳过下载: {outfn}")
        return True
    
    # 下载文件
    try:
        print(f"正在下载: {correct_url}")
        r = requests.get(correct_url, headers=HEADERS, timeout=30, stream=True)
        if r.status_code == 200:
            with open(outfn, "wb") as f:
                for chunk in r.iter_content(1024):
                    f.write(chunk)
            print(f"成功下载到: {outfn}")
            return True
        else:
            print(f"下载失败，HTTP状态码: {r.status_code}")
            return False
    except Exception as e:
        print(f"下载异常: {e}")
        return False

def main():
    # 从log.txt中读取失败的链接
    try:
        with open("./log/log.txt", "r", encoding="utf-8") as f:
            content = f.read()
    except FileNotFoundError:
        print("未找到log.txt文件")
        return
    
    # 解析失败的链接
    pattern = r"下载失败：(.+?)\s*\((.+?)\)"
    matches = re.findall(pattern, content)
    
    print(f"找到 {len(matches)} 个失败的下载项")
    
    for university_name, logo_path in matches:
        # 提取logo文件名
        logo_filename = logo_path.replace("logo-jpg/", "")
        print(f"处理: {university_name} ({logo_filename})")
        download_logo_with_correct_path(logo_filename, university_name)

if __name__ == "__main__":
    main()